// pages/comment/comment.js
var util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '',
    pageNum: 1, // 分页参数
    noList: false,
    commenDetail: {},
    commentList: []
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // options.goodsId = '96'
    console.info('==== options ====', options)
    this.setData({
      goodsId: options.goodsId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      commentList: []
    })
    this.getComment()
  },

  // 获取品论列表
  getComment() {
    wx.get(`${wx.api.commentList}?goodsId=${this.data.goodsId}&pageNum=${this.data.pageNum}`, res => {
      console.log('==== commentList ===', res)
      if (res.rows.length > 0) {
        this.setData({
          commentList: this.data.commentList.concat(res.rows)
        })
      } else {
        if (this.data.pageNum > 1) {
          this.setData({
            noList: true
          })
        }
      }
    }, fail => {})
    wx.get('/api/comment/score?goodsId='+ this.data.goodsId, res => {
      console.log('==== comment ===', res)
      this.setData({
        commenDetail: res.data
      })
    }, fail => {})
  },

  agreethrottle: util.throttle(function(e) {
    let agree = e.currentTarget.dataset['agree']
    console.log(agree)
    if (agree == '0') {
      this.agree(e)
    } 
    // else {
    //   this.deleteAgree(e)
    // }
  }, 5000),

  // 点赞
  agree(e) {
    let id = e.currentTarget.dataset['id']
    let index = e.currentTarget.dataset['index']
    console.log(id)
    wx.post(`/api/comment/agree/${id}`, {}, res => {
      console.log('==== agree ===', res)
      if (res.code == 200) {
        this.setData({
          [`commentList[${index}].isAgree`]: 1,
          [`commentList[${index}].agreeCount`]: this.data.commentList[index].agreeCount + 1
        })
      }
    }, fail => {})
  },

  // 取消点赞
  deleteAgree(e) {
    let id = e.currentTarget.dataset['id']
    let index = e.currentTarget.dataset['index']
    console.log(id)
    wx.post(`/api/comment/deleteAgree/${id}`, {}, res => {
      console.log('==== deleteAgree ===', res)
      if (res.code == 200) {
        this.setData({
          [`commentList[${index}].isAgree`]: 0,
          [`commentList[${index}].agreeCount`]: this.data.commentList[index].agreeCount - 1
        })
      }
    }, fail => {})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.noList) return
    this.data.pageNum ++
    this.getComment()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})